const express = require("express");
const app = express();
const http = require("http").createServer(app);
const { Server } = require("socket.io");
const io = new Server(http);
app.use(express.static("public"));

//#region ws请求封装参数
const queue = [];
const ws = {
  p1(path, cb) {
    queue.push({ role: "p1", path, cb });
  },
  p2(path, cb) {
    queue.push({ role: "p2", path, cb });
  },
  all(path, cb) {
    queue.push({ role: "*", path, cb });
  },
};
function res(obj) {
  const { cb, path, role } = obj;
  cb({
    send(value) {
      sendMessage({ path, role, value });
    },
    ...obj,
  });
}

function sendMessage(msg) {
  io.emit("chat message", msg);
}
//#endregion
let person = 0;
const allRole = {};
io.on("connection", (socket) => {
  person++;
  let role;
  if (!allRole.p1) {
    role = "p1";
  } else if (!allRole.p2) {
    role = "p2";
  } else {
    role = "watching";
  }
  sendMessage({ path: "/start/init", value: { role } });
  //正常响应
  socket.on("chat message", (msg) => {
    //#region ws封装
    const { role, path, value } = msg;
    // console.log(msg);
    if (!role || !path) return sendMessage({ code: 1, msg: "参数错误" });
    queue.forEach((item) => {
      if (item.path === path && (role === item.role || item.role === "*")) {
        res({ role, path, cb: item.cb, value });
      }
    });
    //#endregion
  });
  //退出
  socket.on("break", (name) => {
    console.log("break");
  });
  socket.on("disconnect", () => {
    person--;
  });
});

http.listen(2430, () => {
  console.log("http://127.0.0.1:" + 2430);
});
//#region 移动操作
ws.p1("/key/down", function (res) {
  const { role, path, send } = res;
  send(res.value);
});

ws.p2("/key/down", (res) => {
  const { role, path, send } = res;
  send(res.value);
});

ws.p1("/key/up", function (res) {
  const { role, path, send, value } = res;
  send({ role, path, value });
});

ws.p2("/key/up", (res) => {
  const { role, path, send } = res;
  send(res);
});

ws.all("/start", (res) => {
  const { role, path, send, value } = res;
  if (value && (value.role === "p1" || value.role === "p2")) {
    allRole[value.role] = {};
  }
  send(value);
});
//#endregion

//#region 血量操作
ws.all("/hp", (res) => {
  const { role, path, send, value } = res;
  send({ role, path, value });
});
//#endregion

//#region 分数操作
ws.all("/getState", (res) => {
  const { role, path, send, value } = res;
  send({ role, path, value });
});
//#endregion

//#region 射击操作
ws.all("/fire/j", (res) => {
  const { role, path, send, value } = res;
  send(res.value);
});
//#endregion
//#region 弹幕功能
ws.all("/barrage", (res) => {
  const { role, path, send, value } = res;
  send(res.value);
});
//#endregion
ws.all("/end", (res) => {
  const { role, path, send, value } = res;
  if (value && (value.role === "p1" || value.role === "p2")) {
    delete allRole[value.role];
  }
  send(res);
});
